package com.cd.javacxy.module.web.controller;

import com.cd.javacxy.common.model.entity.CxyLike;
import com.cd.javacxy.common.model.entity.SessionUser;
import com.cd.javacxy.common.model.enums.ResponseCode;
import com.cd.javacxy.common.model.vo.AjaxResponse;
import com.cd.javacxy.common.utils.Constants;
import com.cd.javacxy.exception.BussinessException;
import com.cd.javacxy.module.web.service.CxyLikeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * CxyLike的路由接口服务
 *
 * @author yanghy
 */
@RestController
@Slf4j
public class CxyLikeController {

    /**
     * CxyLikeService服务
     */
    private CxyLikeService cxyLikeService;

    @Autowired
    public void setCxyLikeService(CxyLikeService cxyLikeService) {
        this.cxyLikeService = cxyLikeService;
    }

    @PostMapping("/like/do")
    public AjaxResponse<Object> doLike(HttpSession session, CxyLike like){
        AjaxResponse<Object> ajaxResponse = AjaxResponse.builder().build();
        SessionUser sessionUser = (SessionUser) session.getAttribute(Constants.SESSION_USER_KEY);
        if(sessionUser==null){
            ajaxResponse.setCode(ResponseCode.BUSSINESSERROR.getCode());
            ajaxResponse.setErrorMsg("请先登录");
            return ajaxResponse;
        }
        try {
            this.cxyLikeService.addLike(like);
            ajaxResponse.setCode(ResponseCode.SUCCESS.getCode());
        } catch (BussinessException e) {
            ajaxResponse.setErrorMsg(e.getLocalizedMessage());
            ajaxResponse.setCode(ResponseCode.BUSSINESSERROR.getCode());
            log.error("{}赞出错{}", sessionUser.getUserName(), e.getLocalizedMessage());
        }catch (Exception e) {
            log.error("{}赞出错{}", sessionUser.getUserName(), e.getLocalizedMessage());
            ajaxResponse.setErrorMsg("服务器出错");
            ajaxResponse.setCode(ResponseCode.SERVERERROR.getCode());
        }
        return ajaxResponse;
    }
}
